package com.cetcs.kmga.dataManager.global;

import com.cetcs.kmga.dataManager.dao.hbase.LogPage;
import com.cetcs.kmga.dataManager.util.EhcacheUtil;
import com.cetcs.kmga.dataManager.util.ShiroOper;
import net.sf.ehcache.Element;

import java.util.Date;

/**
 * 日志查询缓存操作
 *
 * @author xutao
 * @version V1.0 创建时间：2017-11-30 13:27
 * Copyright 2017 by CETC
 */
public class LogQueryEhcacheOper {



    /**
     * 存放查询的日志结果到缓存中
     */
    public static void putLogPage(LogPage logPage,String clientIp) {
        //取出缓存的公共对象
        EhcacheUtil ehcacheUtil = new EhcacheUtil(DataManagerConstants.LOG_QUERY_CACHE_CODE);
        String newKey = gerKey()+clientIp;
        //设置查询时间
        logPage.setQueryTime(new Date());
        logPage.setQueryUserId(ShiroOper.getUserId());
        logPage.setQueryUserName(ShiroOper.getUserName());
        logPage.setQueryTime(new Date());
        if (ehcacheUtil.get(newKey) != null) {
            ehcacheUtil.remove(newKey);
        }
        Element newEle = new Element(newKey, logPage);
        ehcacheUtil.put(newEle);
    }

    /**
     * 删除当前用户
     */
    public static void remvoeLogPage() {
        EhcacheUtil ehcacheUtil = new EhcacheUtil(DataManagerConstants.LOG_QUERY_CACHE_CODE);
        ehcacheUtil.remove(gerKey());
    }

    /**
     * 获取当前的LogPage
     *
     * @return
     */
    public static LogPage getLogPage(String clientIp) {
        EhcacheUtil ehcacheUtil = new EhcacheUtil(DataManagerConstants.LOG_QUERY_CACHE_CODE);
        LogPage ret = null;
        String newKey = gerKey()+clientIp;
        if (ehcacheUtil.get(newKey) != null) {
            Element serConfElement = ehcacheUtil.get(newKey);
            ret = (LogPage) serConfElement.getObjectValue();
        }
        return ret;
    }

    /**
     * 生成缓存的key
     *
     * @return
     */
    private static String gerKey() {
        String newKey = DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME + ShiroOper.getUserId();
        return newKey;
    }
    public static String gerMapKey(String servIp) {
        String newKey = DataManagerConstants.SYS_EMAIL_EHCACHE_ELEMENT_NAME + ShiroOper.getUserId()+servIp;
        return newKey;
    }

    /**
     * 获取表的名字
     *
     * @return
     */
    public static String makeH2TbName() {
        Integer userId = ShiroOper.getUserId();
        String tbName = makeH2TbNameByUserId(userId);
        return tbName;
    }

    public static String makeH2TbName(String clientIp) {
        Integer userId = ShiroOper.getUserId();
        String tbName = makeH2TbNameByUserId(userId) + clientIp;
        return tbName;
    }

    /**
     * @param userId
     * @return
     */
    public static String makeH2TbNameByUserId(Integer userId) {
        String tbName = DataManagerConstants.CACHE_H2_TB_NAME + "_" + userId;
        return tbName;
    }
}
